package com.bsb.biz.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.bsb.base.common.util.BeanUtils;
import com.bsb.base.common.util.DateUtils;
import com.bsb.base.common.util.ExportExcel;
import com.bsb.base.common.util.FileUtil;
import com.bsb.base.model.BsbCard;
import com.bsb.base.model.BsbCardBatch;
import com.bsb.base.model.BsbCardBatchExample;
import com.bsb.base.model.BsbCardExample;
import com.bsb.base.model.BsbCardExample.Criteria;
import com.bsb.base.model.BsbFirm;
import com.bsb.base.model.CardBatch;
import com.bsb.base.model.PoiCard;
import com.bsb.biz.service.BsbCardBatchService;
import com.bsb.biz.service.BsbCardService;
import com.bsb.biz.service.BsbFirmService;

@Controller
@RequestMapping("/bsbCardBatch")
public class BsbCardBatchController{
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/bsbCardBatch/list.do";
	
	@Resource
	private BsbCardBatchService bsbCardBatchService;
	@Resource
	private BsbFirmService bsbFirmService;
	@Resource
	private BsbCardService bsbCardService;
	
	@RequiresPermissions("bsbCardBatch:view")
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(
			Model model,
			@RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		BsbCardBatchExample bsbCardBatchExample = new BsbCardBatchExample();
		int totalCount = bsbCardBatchService.countBsbCardBatch(bsbCardBatchExample);
		if(totalCount%pageSize == 0){
			maxPageNum = totalCount/pageSize;
		}else{
			maxPageNum = totalCount/pageSize+1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		}else {
			if(maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		bsbCardBatchExample.setPageIndex((pageNum - 1) * pageSize);
		bsbCardBatchExample.setPageSize(pageSize);
		List<BsbCardBatch> bsbCardBatchs = bsbCardBatchService.getPageBsbCardBatch(bsbCardBatchExample);
		List<CardBatch> list = new ArrayList<CardBatch>();
		for (BsbCardBatch bsbCardBatch : bsbCardBatchs) {
			CardBatch cardBatch = new CardBatch();
			Long firmId = bsbCardBatch.getFirmId();
			BsbFirm bsbFirmByAccount = bsbFirmService.getBsbFirmByAccount(firmId.intValue());
			if(null != bsbFirmByAccount){
				cardBatch.setFirmName(bsbFirmByAccount.getName());
			}
			BeanUtils.copyProperties(cardBatch, bsbCardBatch);
			list.add(cardBatch);
		}
		
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if(totalCount%pageSize == 0){
			model.addAttribute("maxPageNum", totalCount/pageSize);
		}else{
			model.addAttribute("maxPageNum", totalCount/pageSize+1);
		}
		model.addAttribute("bsbCardBatchs", list);
		return "/BsbCardBatch/list";
	}
	
	@RequiresPermissions("bsbCardBatch:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String toAdd(Model model) {
		return "/BsbCardBatch/add";
	}

	@RequiresPermissions("bsbCardBatch:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String add(Model model, 
			@RequestParam(value = "firmId", required = true) Long firmId,RedirectAttributes redirectAttributes,
			@ModelAttribute("bsbCardBatch") BsbCardBatch bsbCardBatch) {
		if(firmId == 0){
			redirectAttributes.addFlashAttribute("msg", "请选择事务所");
			return "/BsbCardBatch/add";
		}
		Long num = bsbCardBatch.getNum();
		if(num <=0){
			redirectAttributes.addFlashAttribute("msg", "请填写会员卡数量");
			return "/BsbCardBatch/add";
		}
		bsbCardBatchService.addBatchCard(num,firmId);
		return redirect;
	}
	
	@RequiresPermissions("bsbCardBatch:delete")
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
	public String del(Model model,
			@PathVariable("id") Long id) {
		bsbCardBatchService.delBsbCardBatchById(id);
		return redirect;
	}
	
	@RequiresPermissions("bsbCardBatch:update")
	@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
	public String toEdit(Model model,
			@PathVariable("id") Long id) {
		BsbCardBatch bsbCardBatch = bsbCardBatchService.getBsbCardBatchById(id);
		model.addAttribute("bsbCardBatch", bsbCardBatch);
		return "/BsbCardBatch/edit";
	}

	@RequiresPermissions("bsbCardBatch:update")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String edit(Model model, @ModelAttribute("bsbCardBatch") BsbCardBatch bsbCardBatch) {
		bsbCardBatchService.updateBsbCardBatch(bsbCardBatch);
		return redirect;
	}
	
	@RequiresPermissions("bsbCardBatch:view")
	@RequestMapping(value = "/{id}/view", method = RequestMethod.GET)
	public String view(Model model,
			@PathVariable("id") Long id) {
		BsbCardBatch bsbCardBatch = bsbCardBatchService.getBsbCardBatchById(id);
		model.addAttribute("bsbCardBatch", bsbCardBatch);
		return "/BsbCardBatch/view";
	}
	
	@RequiresPermissions("bsbCardBatch:export")
	@RequestMapping(value = "export/{id}", method = RequestMethod.GET)
	public void export(HttpServletRequest request, HttpServletResponse response, @PathVariable String id) {
		BsbCardExample example = new BsbCardExample();
		Criteria criteria = example.createCriteria();
		criteria.andBatchIdEqualTo(Long.valueOf(id));
		List<BsbCard> cards = bsbCardService.selectByExample(example);
		List<PoiCard> dataset = new ArrayList<PoiCard>();
		for (BsbCard bsbCard : cards) {
			Long batchId = bsbCard.getBatchId();
			Long cardId = bsbCard.getId();
			String pwd = bsbCard.getSecurityCode();
			PoiCard card = new PoiCard(batchId, cardId, pwd);
			dataset.add(card);
		}
		String formatDate = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");
		ExportExcel<PoiCard> ex = new ExportExcel<>();
		String[] headers = new String[] { "批号", "卡号", "密码" };
		String dir = "/home/images/poi/";
		try {
			String title = formatDate + System.currentTimeMillis();
			File file = new File(dir);
			if (file.exists()) {
				File[] files = file.listFiles();
				File temp = null;
				for (int i = 0; i < files.length; i++) {
					if (files[i].isFile()) {
						temp = new File(dir + files[i].getName());
						if (temp.exists() && temp.isFile()) {
							temp.delete();
						}

					}
				}
			}
			OutputStream out = new FileOutputStream(dir + title);
			ex.exportExcel(title, headers, dataset, out, "yyyy-MM-dd");
			FileUtil.downloadFile(request, response, dir + title, "第" + id + "批会员卡" + formatDate + ".xls");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
